import React, { useState, useEffect } from 'react';
import { Modal, Tabs, Table, Spin, Button, message, Tag, Descriptions, Timeline, Pagination } from 'antd';
import {
    getGroupById,
    Group,
    getGroupStudents,
    getGroupTeachers,
    Student,
    Teacher,
    getGroupEvents,
    EventLog
} from '@/utils/api/group/group';
import moment from 'moment';

interface GroupDetailModalProps {
    visible: boolean;
    groupId: number | null;
    onCancel: () => void;
}

const GroupDetailModal: React.FC<GroupDetailModalProps> = ({ visible, groupId, onCancel }) => {
    const [loading, setLoading] = useState<boolean>(false);
    const [groupInfo, setGroupInfo] = useState<Group | null>(null);
    const [students, setStudents] = useState<Student[]>([]);
    const [teachers, setTeachers] = useState<Teacher[]>([]);
    const [activeTab, setActiveTab] = useState<string>('info');
    const [groupEvents, setGroupEvents] = useState<EventLog[]>([]);
    const [eventsLoaded, setEventsLoaded] = useState<boolean>(false);

    // 分页
    const [studentsPagination, setStudentsPagination] = useState({
        current: 1,
        pageSize: 10,
        total: 0,
        pages: 0
    });

    const [teachersPagination, setTeachersPagination] = useState({
        current: 1,
        pageSize: 10,
        total: 0,
        pages: 0
    });

    // 获取小组详情和关联数据
    useEffect(() => {
        if (visible && groupId) {
            fetchGroupDetail();
        } else {
            // 重置状态
            setGroupInfo(null);
            setStudents([]);
            setTeachers([]);
            setGroupEvents([]);
            setEventsLoaded(false);
            setActiveTab('info');

            // 重置分页状态
            setStudentsPagination({
                current: 1,
                pageSize: 10,
                total: 0,
                pages: 0
            });
            setTeachersPagination({
                current: 1,
                pageSize: 10,
                total: 0,
                pages: 0
            });
        }
    }, [visible, groupId]);

    // 监听tab切换
    useEffect(() => {
        if (visible && groupId) {
            if (activeTab === 'students') {
                fetchStudents(studentsPagination.current, studentsPagination.pageSize);
            } else if (activeTab === 'teachers') {
                fetchTeachers(teachersPagination.current, teachersPagination.pageSize);
            } else if (activeTab === 'events' && !eventsLoaded) {
                fetchGroupEvents();
            }
        }
    }, [activeTab, visible, groupId]);

    const fetchGroupDetail = async () => {
        try {
            setLoading(true);
            const groupResponse = await getGroupById(groupId!);
            setGroupInfo(groupResponse.data);
        } catch (error) {
            console.error('获取小组详情失败:', error);

        } finally {
            setLoading(false);
        }
    };

    const fetchStudents = async (pageNum: number = 1, pageSize: number = 10) => {
        try {
            setLoading(true);
            const response = await getGroupStudents(groupId!, pageNum, pageSize);

            // 处理分页数据结构
            let studentsData = [];
            let total = 0;
            let pages = 0;

            if (response.data && response.data.list) {
                studentsData = response.data.list;
                total = response.data.total || 0;
                pages = response.data.pages || 0;
            } else if (Array.isArray(response.data)) {
                studentsData = response.data;
                total = response.data.length;
                pages = 1;
            }

            setStudents(studentsData);
            setStudentsPagination(prev => ({
                ...prev,
                current: pageNum,
                pageSize,
                total,
                pages
            }));
        } catch (error) {
            console.error('获取小组成员失败:', error);

            setStudents([]);
        } finally {
            setLoading(false);
        }
    };

    const fetchTeachers = async (pageNum: number = 1, pageSize: number = 10) => {
        try {
            setLoading(true);
            const response = await getGroupTeachers(groupId!, pageNum, pageSize);

            // 处理分页数据结构
            let teachersData = [];
            let total = 0;
            let pages = 0;

            if (response.data && response.data.list) {
                teachersData = response.data.list;
                total = response.data.total || 0;
                pages = response.data.pages || 0;
            } else if (Array.isArray(response.data)) {
                teachersData = response.data;
                total = response.data.length;
                pages = 1;
            }

            setTeachers(teachersData);
            setTeachersPagination(prev => ({
                ...prev,
                current: pageNum,
                pageSize,
                total,
                pages
            }));
        } catch (error) {
            console.error('获取小组教师失败:', error);
            setTeachers([]);
        } finally {
            setLoading(false);
        }
    };

    // 获取小组事件记录
    const fetchGroupEvents = async () => {
        try {
            setLoading(true);
            const response = await getGroupEvents(groupId!);

            if (response.code === 200) {
                let events: EventLog[] = [];

                if (Array.isArray(response.data)) {
                    events = response.data.map((event: any) => ({
                        id: event.id,
                        groupId: event.groupId,
                        studentId: event.studentId,
                        studentName: event.studentName,
                        logType: event.logType,
                        createTime: event.createTime,
                        log: event.log,
                        description: event.log
                    }));
                }

                setGroupEvents(events);
            } else {
                setGroupEvents([]);
            }
            setEventsLoaded(true);
        } catch (error) {
            console.error('获取小组事件记录失败:', error);
            setGroupEvents([]);
            setEventsLoaded(true);
        } finally {
            setLoading(false);
        }
    };

    // 处理学生分页变化
    const handleStudentsPageChange = (page: number, pageSize?: number) => {
        const newPageSize = pageSize || studentsPagination.pageSize;
        fetchStudents(page, newPageSize);
    };

    // 处理教师分页变化
    const handleTeachersPageChange = (page: number, pageSize?: number) => {
        const newPageSize = pageSize || teachersPagination.pageSize;
        fetchTeachers(page, newPageSize);
    };

    const tabItems = [
        {
            key: 'info',
            label: '基本信息',
            children: groupInfo ? (
                <div>
                    <p><strong>小组名称：</strong>{groupInfo.name}</p>
                    <p><strong>成立时间：</strong>{moment(groupInfo.bornTime).format('YYYY-MM-DD')}</p>
                    <p><strong>小组简介：</strong>{groupInfo.profile}</p>
                    <p><strong>当前人数：</strong>{groupInfo.number}</p>
                    <p><strong>小组热度：</strong>{groupInfo.hot}</p>
                    <p><strong>指导老师：</strong>
                        {groupInfo.teacherName && groupInfo.teacherName.length > 0 ? (
                            groupInfo.teacherName.map((name, index) => (
                                <Tag key={index} color="blue" style={{ margin: '2px' }}>
                                    {name}
                                </Tag>
                            ))
                        ) : (
                            '暂无'
                        )}
                    </p>
                    <p><strong>创建时间：</strong>{moment(groupInfo.createTime).format('YYYY-MM-DD HH:mm:ss')}</p>
                </div>
            ) : null,
        },
        {
            key: 'students',
            label: `小组成员`,
            children: (
                <div>
                    <Table
                        dataSource={students}
                        rowKey="id"
                        pagination={false}
                        columns={[
                            {
                                title: '学号',
                                dataIndex: 'studentNumber',
                                key: 'studentNumber',
                                render: (studentNumber: string) => studentNumber || '-',
                            },
                            {
                                title: '姓名',
                                dataIndex: 'name',
                                key: 'name',
                            },
                            {
                                title: '性别',
                                dataIndex: 'sex',
                                key: 'sex',
                                render: (sex: number) => sex === 0 ? '女' : '男',
                            },
                            {
                                title: '年龄',
                                dataIndex: 'age',
                                key: 'age',
                            },
                            {
                                title: '年级',
                                dataIndex: 'grade',
                                key: 'grade',
                                render: (grade: any) => grade ? `${grade}级` : '-',
                            },
                            {
                                title: '院系',
                                dataIndex: 'department',
                                key: 'department',
                            },
                            {
                                title: '专业',
                                dataIndex: 'major',
                                key: 'major',
                            },
                            {
                                title: '手机号',
                                dataIndex: 'phone',
                                key: 'phone',
                            },
                        ]}
                    />
                    {studentsPagination.total > 0 && (
                        <div style={{ marginTop: 16, textAlign: 'right' }}>
                            <Pagination
                                current={studentsPagination.current}
                                pageSize={studentsPagination.pageSize}
                                total={studentsPagination.total}
                                onChange={handleStudentsPageChange}

                                showTotal={(total, range) => `第 ${range[0]}-${range[1]} 条，共 ${total} 条记录`}
                            />
                        </div>
                    )}
                </div>
            ),
        },
        {
            key: 'teachers',
            label: `小组教师`,
            children: (
                <div>
                    <Table
                        dataSource={teachers}
                        rowKey="id"
                        pagination={false}
                        columns={[
                            {
                                title: '姓名',
                                dataIndex: 'name',
                                key: 'name',
                            },
                            {
                                title: '性别',
                                dataIndex: 'sex',
                                key: 'sex',
                                render: (sex: number) => sex === 0 ? '女' : '男',
                            },
                            {
                                title: '年龄',
                                dataIndex: 'age',
                                key: 'age',
                            },
                            {
                                title: '职务',
                                dataIndex: 'position',
                                key: 'position',
                            },
                            {
                                title: '手机号',
                                dataIndex: 'phone',
                                key: 'phone',
                            }
                        ]}
                    />
                    {teachersPagination.total > 0 && (
                        <div style={{ marginTop: 16, textAlign: 'right' }}>
                            <Pagination
                                current={teachersPagination.current}
                                pageSize={teachersPagination.pageSize}
                                total={teachersPagination.total}
                                onChange={handleTeachersPageChange}
                                showTotal={(total, range) => `第 ${range[0]}-${range[1]} 条，共 ${total} 条记录`}
                            />
                        </div>
                    )}
                </div>
            ),
        },
        {
            key: 'events',
            label: '事件记录',
            children: (
                <div style={{ padding: '20px', maxHeight: '400px', overflowY: 'auto' }}>
                    <Timeline>
                        {groupEvents.length > 0 ? (
                            groupEvents.map((event, index) => (
                                <Timeline.Item key={index}>
                                    <p>{event.log}</p>
                                    <p style={{ color: '#999', fontSize: '12px' }}>
                                        {moment(event.createTime).format('YYYY-MM-DD HH:mm:ss')}
                                    </p>
                                </Timeline.Item>
                            ))
                        ) : (
                            <p>暂无事件记录</p>
                        )}
                    </Timeline>
                </div>
            ),
        },
    ];

    return (
        <Modal
            title="小组详情"
            open={visible}
            onCancel={onCancel}
            footer={[
                <Button key="close" onClick={onCancel}>
                    关闭
                </Button>,
            ]}
            width={1000}
            destroyOnClose
        >
            <Spin spinning={loading}>
                <Tabs
                    activeKey={activeTab}
                    items={tabItems}
                    onChange={setActiveTab}
                />
            </Spin>
        </Modal>
    );
};

export default GroupDetailModal;